/**
 * 账户服务
 * 处理账户相关的业务逻辑
 */
const { User, Account } = require('../models');
const jwt = require('jsonwebtoken');
const config = require('../config/config');

class AccountService {
  /**
   * 用户登录
   * @param {string} phone - 手机号
   * @param {string} password - 密码
   * @returns {Promise<Object>} 登录成功后的账户信息
   */
  async login(phone, password) {
    // 查询用户
    const user = await User.findOne({
      where: { phone }
    });

    // 验证用户是否存在和密码是否正确
    if (!user || !(await user.validatePassword(password))) {
      throw new Error('账号或密码错误');
    }

    // 查询或创建账户
    let account = await Account.findOne({
      where: { user_id: user.id }
    });

    if (!account) {
      // 创建账户
      account = await Account.create({
        user_id: user.id,
        username: user.username,
        password: user.password,
        phone: user.phone
      });
    } else {
      // 更新账户信息
      await account.update({
        username: user.username,
        phone: user.phone
      });
    }

    // 生成token
    const token = jwt.sign(
      { id: user.id, username: user.username },
      config.jwtSecret,
      { expiresIn: '24h' }
    );

    // 更新token
    await account.update({ token });

    // 返回账户信息
    return {
      id: account.id,
      username: account.username,
      phone: account.phone,
      token
    };
  }

  /**
   * 获取账户信息
   * @param {number} userId - 用户ID
   * @returns {Promise<Object>} 账户信息
   */
  async getAccountInfo(userId) {
    const account = await Account.findOne({
      where: { user_id: userId },
      include: [{ model: User, as: 'user' }]
    });

    if (!account) {
      throw new Error('账户不存在');
    }

    return {
      id: account.id,
      username: account.username,
      phone: account.phone,
      token: account.token,
      user: {
        id: account.user.id,
        username: account.user.username,
        phone: account.user.phone,
        register_time: account.user.register_time
      }
    };
  }

  /**
   * 更新账户信息
   * @param {number} userId - 用户ID
   * @param {Object} data - 要更新的数据
   * @returns {Promise<Object>} 更新后的账户信息
   */
  async updateAccount(userId, data) {
    const account = await Account.findOne({
      where: { user_id: userId }
    });

    if (!account) {
      throw new Error('账户不存在');
    }

    // 更新账户信息
    await account.update(data);

    // 更新关联的用户信息
    await User.update(data, {
      where: { id: userId }
    });

    // 返回更新后的账户信息
    return await this.getAccountInfo(userId);
  }
}

module.exports = new AccountService();